package hander

import (
	"egg-master/cache"
	"egg-master/moderl"
	"egg-master/pkg"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	var user moderl.User
	err := moderl.DB.Where("username=?", username).First(&user).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5Str(password) {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登陆成功",
		"data": user,
	})
	return
}
func Add(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := moderl.User{

		Username: username,
		Password: password,
	}
	err := moderl.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	//设置缓存
	redis_key := "user_redis_key" + strconv.Itoa(int(data.ID)) //定义一个名字+表的id(转化为字符串)
	var user moderl.User                                       //定义一个数字
	moderl.DB.Where("id=?", data.ID).First(&user)              //在数组中查询
	jsonData, _ := json.Marshal(user)                          //转化为json格式
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var user moderl.User
	redis_key := "detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		//获取缓存的数据
		moderl.DB.Where("id=?", id).First(&user)
		//获取转化json格式
		jsonData, _ := json.Marshal(user)
		//保存到redis中
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &user) //
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": user,
	})
	return
}
func Del(c *gin.Context) {
	id := c.Query("id")
	err := moderl.DB.Where("id=?", id).Delete(&moderl.User{}).Error
	if err != nil {

		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	redis_key := "user" + id
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "删除成功",
	})
	return
}
